﻿using System;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using AccountManagement.BussinessObjects;
using AccountManagement.DataAccess;

namespace AccountManagement
{
    /// <summary>
    /// Interaction logic for FrmThu.xaml
    /// </summary>
    public partial class FrmThuChi
    {
        private readonly bool _isUpdate;
        private readonly bool _isThu;
        private tblPhieuThuChi _objPhieuThuChi;
        private bool _isValidated;

        public FrmThuChi()
        {
            InitializeComponent();
        }

        public FrmThuChi(bool isThu)
        {
            InitializeComponent();
            _isUpdate = false;
            _isThu = isThu;

            if (_isThu)
            {
                lblPhieuSo.Content = Utils.GetPhieuSoThu();
                lblQuyenSo.Content = Utils.GetQuyenSoThu();
            }
            else
            {
                Title = "Phiếu Chi";
                lblTitle.Content = "PHIẾU CHI";
                lblLyDo.Content = "Lý do chi";
                lblPhieuSo.Content = Utils.GetPhieuSoChi();
                lblQuyenSo.Content = Utils.GetQuyenSoChi();
            }

            dtpNgayThang.SelectedDate = DateTime.Now;
            try
            {
                lblDonvi.Content = ConfigurationManager.AppSettings.Get("TenCongTy");
                lblDiachi.Content = ConfigurationManager.AppSettings.Get("DiaChi");
            }
            catch (Exception)
            {

            }

            //lblTitle.Visibility = Visibility.Hidden;
            _isValidated = true;
        }

        public FrmThuChi(tblPhieuThuChi objPhieuThuChi, bool isThu)
        {
            InitializeComponent();
            _isUpdate = true;
            _isThu = isThu;

            if (!_isThu)
            {
                Title = "Phiếu Chi";
                lblTitle.Content = "PHIẾU CHI";
                lblLyDo.Content = "Lý do chi";
            }

            _objPhieuThuChi = objPhieuThuChi;
            FillData(objPhieuThuChi);

            try
            {
                lblDonvi.Content = ConfigurationManager.AppSettings.Get("TenCongTy");
                lblDiachi.Content = ConfigurationManager.AppSettings.Get("DiaChi");
            }
            catch (Exception)
            {

            }

            //lblTitle.Visibility = Visibility.Hidden;
            _isValidated = true;
        }

        private void FillData(tblPhieuThuChi objPhieuThuChi)
        {
            try
            {
                dtpNgayThang.SelectedDate = objPhieuThuChi.NgayThang;
                lblQuyenSo.Content = objPhieuThuChi.QuyenSo.ToString();
                lblPhieuSo.Content = objPhieuThuChi.PhieuSo.ToString();
                txtTKCo.Text = objPhieuThuChi.TKCo.ToString();
                txtTKNo.Text = objPhieuThuChi.TKNo.ToString();
                if (objPhieuThuChi.TKThue != null)
                {
                    txtTKThue.Text = objPhieuThuChi.TKThue.ToString();
                    txtThue.Text = objPhieuThuChi.Thue.ToString();
                }
                txtName.Text = objPhieuThuChi.HoTen;
                txtAddress.Text = objPhieuThuChi.DiaChi;
                txtReason.Text = objPhieuThuChi.LyDo;
                txtAmount.Text = objPhieuThuChi.Sotien.ToString("0,0");
                txtTextWrite.Text = objPhieuThuChi.VietBangChu;
                txtAttach.Text = objPhieuThuChi.KemTheo;
                txtConfirm.Text = objPhieuThuChi.DaNhanDu;
            }
            catch (Exception)
            {

            }
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!ValidateData())
                    return;

                var canClose = _isUpdate ? Update() : Add();

                if (canClose)
                    Close();
            }
            catch (Exception)
            {

            }
        }

        private bool ValidateData()
        {
            if (string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                MessageBox.Show("'Họ và tên' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtName.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtAddress.Text.Trim()))
            {
                MessageBox.Show("'Địa chỉ' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtAddress.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtReason.Text.Trim()))
            {
                MessageBox.Show("'Lý do thu' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtReason.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtAmount.Text.Trim()))
            {
                MessageBox.Show("'Số tiền' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtAmount.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtTextWrite.Text.Trim()))
            {
                MessageBox.Show("'Viết bằng chữ' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtTextWrite.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtAttach.Text.Trim()))
            {
                MessageBox.Show("'Kèm theo' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtAttach.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtConfirm.Text.Trim()))
            {
                MessageBox.Show("'Đã nhận đủ' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtAttach.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtTKCo.Text.Trim()))
            {
                MessageBox.Show("'Tài khoản có' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtTKCo.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(txtTKNo.Text.Trim()))
            {
                MessageBox.Show("'Tài khoản nợ' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtTKNo.Focus();
                return false;
            }

            if (!string.IsNullOrEmpty(txtTKThue.Text.Trim()) && string.IsNullOrEmpty(txtThue.Text.Trim()))
            {
                MessageBox.Show("'Thuế' không thể bỏ trống", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                txtThue.Focus();
                return false;
            }

            if (!_isValidated)
            {
                MessageBox.Show("Nhập sai định dạng, xem chi tiết các ô màu đỏ.", "Lỗi", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }

            return true;
        }

        private bool Add()
        {
            try
            {
                var objIncomingBO = new IncomingBO();
                var objPhieuThuChi = new tblPhieuThuChi();

                BuildObject(objPhieuThuChi);

                var ret = objIncomingBO.Insert(objPhieuThuChi);

                // Message base on Return value
                Utils.ShowMessage(ret);
                // Focus on error textbox
                switch (ret)
                {
                    case Constants.Errors.TK_CO_NOT_EXISTED:
                        txtTKCo.Focus();
                        break;
                    case Constants.Errors.TK_NO_NOT_EXISTED:
                        txtTKNo.Focus();
                        break;
                    case Constants.Errors.TK_THUE_NOT_EXISTED:
                        txtTKThue.Focus();
                        break;
                }

                if (ret == Constants.Errors.NONE_ADD_PHIEUCHI || ret == Constants.Errors.NONE_ADD_PHIEUTHU)
                {
                    // Update MainWindow
                    ((MainWindow)Application.Current.MainWindow).LoadData();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void BuildObject(tblPhieuThuChi objPhieuThuChi)
        {
            objPhieuThuChi.QuyenSo = Convert.ToInt32(lblQuyenSo.Content.ToString());
            objPhieuThuChi.PhieuSo = Convert.ToInt32(lblPhieuSo.Content.ToString());
            objPhieuThuChi.NgayThang = Convert.ToDateTime(dtpNgayThang.SelectedDate);
            objPhieuThuChi.TKNo = Convert.ToInt32(txtTKNo.Text.Trim());
            objPhieuThuChi.TKCo = Convert.ToInt32(txtTKCo.Text.Trim());
            if (!string.IsNullOrEmpty(txtTKThue.Text.Trim()))
                objPhieuThuChi.TKThue = Convert.ToInt32(txtTKThue.Text.Trim());
            if (!string.IsNullOrEmpty(txtThue.Text.Trim()))
                objPhieuThuChi.Thue = Convert.ToInt32(txtThue.Text.Trim());
            objPhieuThuChi.HoTen = txtName.Text;
            objPhieuThuChi.DiaChi = txtAddress.Text;
            objPhieuThuChi.LyDo = txtReason.Text;
            objPhieuThuChi.Sotien = Convert.ToInt32(txtAmount.Text.Trim().Replace(",", ""));
            objPhieuThuChi.VietBangChu = txtTextWrite.Text;
            objPhieuThuChi.KemTheo = txtAttach.Text;
            objPhieuThuChi.DaNhanDu = txtConfirm.Text;
            objPhieuThuChi.IsIncoming = _isThu;
        }

        private bool Update()
        {
            try
            {
                var objIncomingBO = new IncomingBO();

                //_objPhieuThuChi.QuyenSo = Convert.ToInt32(lblQuyenSo.Content.ToString());
                //_objPhieuThuChi.PhieuSo = Convert.ToInt32(lblPhieuSo.Content.ToString());
                //_objPhieuThuChi.NgayThang = Convert.ToDateTime(dtpNgayThang.SelectedDate);
                //_objPhieuThuChi.TKNo = Convert.ToInt32(txtTKNo.Text.Trim());
                //_objPhieuThuChi.TKCo = Convert.ToInt32(txtTKCo.Text.Trim());
                //if (!string.IsNullOrEmpty(txtTKThue.Text.Trim()))
                //    _objPhieuThuChi.TKThue = Convert.ToInt32(txtTKThue.Text.Trim());
                //if (!string.IsNullOrEmpty(txtThue.Text.Trim()))
                //    _objPhieuThuChi.Thue = Convert.ToInt32(txtThue.Text.Trim());
                //_objPhieuThuChi.HoTen = txtName.Text;
                //_objPhieuThuChi.DiaChi = txtAddress.Text;
                //_objPhieuThuChi.LyDo = txtReason.Text;
                //_objPhieuThuChi.Sotien = Convert.ToInt32(txtAmount.Text.Trim().Replace(",", ""));
                //_objPhieuThuChi.VietBangChu = txtTextWrite.Text;
                //_objPhieuThuChi.KemTheo = txtAttach.Text;
                //_objPhieuThuChi.DaNhanDu = txtConfirm.Text;
                //_objPhieuThuChi.IsIncoming = _isThu;

                BuildObject(_objPhieuThuChi);

                var ret = objIncomingBO.Update(_objPhieuThuChi);

                // Message base on Return value
                Utils.ShowMessage(ret);
                // Focus on error textbox
                switch (ret)
                {
                    case Constants.Errors.TK_CO_NOT_EXISTED:
                        txtTKCo.Focus();
                        break;
                    case Constants.Errors.TK_NO_NOT_EXISTED:
                        txtTKNo.Focus();
                        break;
                    case Constants.Errors.TK_THUE_NOT_EXISTED:
                        txtTKThue.Focus();
                        break;
                }

                if (ret == Constants.Errors.NONE_EDIT_PHIEUCHI || ret == Constants.Errors.NONE_EDIT_PHIEUTHU)
                {
                    // Update MainWindow
                    ((MainWindow)Application.Current.MainWindow).LoadData();
                    return true;
                }
                return false;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                var textBox = (TextBox)sender;
                if (textBox == null) return;

                if (string.IsNullOrEmpty(textBox.Text.Trim()) && (textBox.Name == "txtTKThue" || textBox.Name == "txtThue"))
                {
                    if (txtTKCo.BorderBrush != Brushes.Red &&
                        txtTKNo.BorderBrush != Brushes.Red &&
                        txtTKThue.BorderBrush != Brushes.Red &&
                        txtThue.BorderBrush != Brushes.Red &&
                        txtAmount.BorderBrush != Brushes.Red)
                        _isValidated = true;

                    return;
                }

                //var regEx = new Regex(@"^[-+]?\d*\.?\d*$"); // Matches any floating point numer/numeric string, including optional sign character (+ or -). Also matches empty strings.
                var regEx = new Regex(@"^(((\d{1,3})(,\d{3})*)|(\d+))(.\d+)?$"); // validates numbers, with or without decimal places, and comma 1000 separators.
                //var regEx = new Regex(@"^[-+]?\d+(\.\d+)?$"); // This matches any real number, with optional decimal point and numbers after the decimal, and optional positive (+) or negative (-) designation.

                if (!regEx.IsMatch(textBox.Text.Trim()))
                {
                    textBox.BorderBrush = Brushes.Red;
                    textBox.ToolTip = "Chỉ được phép nhập số.";
                    _isValidated = false;
                }
                else
                {
                    textBox.BorderBrush = txtName.BorderBrush;

                    if (txtTKCo.BorderBrush != Brushes.Red &&
                        txtTKNo.BorderBrush != Brushes.Red &&
                        txtTKThue.BorderBrush != Brushes.Red &&
                        txtThue.BorderBrush != Brushes.Red &&
                        txtAmount.BorderBrush != Brushes.Red)
                        _isValidated = true;
                }

                // Format thousand separator
                if (textBox.Name == "txtAmount")
                {
                    textBox.Text = string.Format("{0:0,0}", Convert.ToDouble(textBox.Text));
                }
            }
            catch (Exception)
            {

            }
        }

        private void txtAmount_GotFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                txtAmount.Text = txtAmount.Text.Replace(",", "");
            }
            catch (Exception)
            {
                
            }
        }

        private void btnPrint_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnPrintPreview_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_objPhieuThuChi == null)
                    _objPhieuThuChi = new tblPhieuThuChi();
                BuildObject(_objPhieuThuChi);

                var frmReport = new FrmReport(_objPhieuThuChi)
                                    {
                                        Owner = this,
                                        WindowStartupLocation = WindowStartupLocation.CenterOwner,
                                        ShowInTaskbar = false
                                    };
                frmReport.ShowDialog();
            }
            catch (Exception)
            {
                
            }
        }
    }
}